package com.newenergy.wisehome.services;

import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by kyx on 2018/1/5.
 */
public class AppStateService extends Service {
    public static final String TAG = "AppStateService";
    private MyThread myThread = null;
    private static class MyThread extends Thread {
        private Context context;
        private boolean isRun = true;
        private MyThread(Context context) {
            this.context = context;
        }
        public void setStop() {
            isRun = false;
        }
        @Override
        public void run() {
            while (isRun) {
                try {//com.tencent.mm
                    TimeUnit.SECONDS.sleep(2);
                    String packName = getTopApp(context);
                    Log.e(TAG,"home==="+packName);
                    if (!TextUtils.isEmpty(packName)){
                        if (packName.equals("com.miui.home")){//小米桌面
                            /*EventBus.getDefault().post(new MyEvent(SPEECH_ENABLE, true));
                            SPUtil.put(SPEECH_ENABLE, true);*/
                            Intent intent = new Intent(context, BaiDuService.class);
                            context.startService(intent);
                        }else if (packName.equals("com.huawei.android.launcher")){//华为桌面
                            /*EventBus.getDefault().post(new MyEvent(SPEECH_ENABLE, true));
                            SPUtil.put(SPEECH_ENABLE, true);*/
                            Intent intent = new Intent(context, BaiDuService.class);
                            context.startService(intent);
                        }else if (packName.equals("com.meizu.flyme.launcher")){//魅族桌面
                            /*EventBus.getDefault().post(new MyEvent(SPEECH_ENABLE, true));
                            SPUtil.put(SPEECH_ENABLE, true);*/
                            Intent intent = new Intent(context, BaiDuService.class);
                            context.startService(intent);
                        }else  if (packName.equals("com.google.android.googlequicksearchbox")){//Nexus 6P
                            Intent intent = new Intent(context, BaiDuService.class);
                            context.startService(intent);
                        }
                        else if (packName.equals("com.newenergy.balllight")){//本应用
                            /*EventBus.getDefault().post(new MyEvent(SPEECH_ENABLE, true));
                            SPUtil.put(SPEECH_ENABLE, true);*/
                            Intent intent = new Intent(context, BaiDuService.class);
                            context.startService(intent);
                        }
                        else if (!packName.equals("com.newenergy.balllight")){//除了本应用的包名
                            /*EventBus.getDefault().post(new MyEvent(SPEECH_ENABLE, false));
                            SPUtil.put(SPEECH_ENABLE, false);*/
                            Intent intent = new Intent(context, BaiDuService.class);
                            intent.setAction("stop service");
                            context.stopService(intent);
                        }

                    }
//                    getTopApp(context);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }


        private String getTopApp(Context context) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                UsageStatsManager m = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
                if (m != null) {
                    long now = System.currentTimeMillis();
                    //获取60秒之内的应用数据
                    List<UsageStats> stats = m.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 60 * 1000, now);
//                    Log.i(TAG, "Running app number in last 60 seconds : " + stats.size());

                    String topActivity = "";

                    //取得最近运行的一个app，即当前运行的app
                    if ((stats != null) && (!stats.isEmpty())) {
                        int j = 0;
                        for (int i = 0; i < stats.size(); i++) {
                            if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
                                j = i;
                            }
                        }
                        topActivity = stats.get(j).getPackageName();
                    }
//                    Log.i(TAG, "top running app is : "+topActivity);
                    return topActivity;
                }
            }
            return null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myThread = new MyThread(this);
        myThread.start();
        Log.i(TAG, "Service is start.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        myThread.setStop();
        Log.i(TAG, "Service is stop.");
    }
}
